package com.example.limit.service;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.time.Duration;
import java.util.Collections;
import java.util.concurrent.TimeUnit;

@Service
public class RedisCounterService {
    
    private final RedisTemplate<String, Object> redisTemplate;
    
    public RedisCounterService(RedisTemplate<String, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }
    
    /**
     * 增加计数并设置过期时间
     */
    public Long increment(String key, int quantity, Duration expireTime) {
        String script = "local current = redis.call('incrby', KEYS[1], ARGV[1]) " +
                       "if tonumber(current) == tonumber(ARGV[1]) then " +
                       "redis.call('expire', KEYS[1], ARGV[2]) end " +
                       "return current";
        
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script, Long.class);
        return redisTemplate.execute(redisScript, Collections.singletonList(key), quantity, expireTime.getSeconds());
    }
    
    /**
     * 获取当前计数
     */
    public Integer getCount(String key) {
        Object value = redisTemplate.opsForValue().get(key);
        return value != null ? Integer.parseInt(value.toString()) : 0;
    }
    
    /**
     * 检查是否超过限制
     */
    public boolean isExceedLimit(String key, int limit, int quantity, Duration expireTime) {
        Integer current = getCount(key);
        if (current + quantity > limit) {
            return true;
        }
        increment(key, quantity, expireTime);
        return false;
    }
    
    /**
     * 删除计数
     */
    public void deleteCount(String key) {
        redisTemplate.delete(key);
    }
    
    /**
     * 生成Redis键
     */
    public String generateKey(String prefix, String... params) {
        return prefix + ":" + String.join(":", params);
    }
}